package com.googlecode.jwsm;

import java.io.*;
import java.lang.reflect.*;

import org.jcommon.xml.*;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;

/**
 * @author Matthew D. Hicks
 *
 */
public class XSLT {
	public static final int INCOMING = 1;
	public static final int OUTGOING = 2;
	
	private String name;
	private String filename;
	private String defaultAssociation;
	private int type;
	
	public String getDefaultAssociation() {
		return defaultAssociation;
	}
	
	public void setDefaultAssociation(String defaultAssociation) {
		this.defaultAssociation = defaultAssociation;
	}
	
	public String getFilename() {
		return filename;
	}
	
	public void setFilename(String filename) {
		this.filename = filename;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public int getType() {
		return type;
	}
	
	public void setType(int type) {
		this.type = type;
	}
	
	public boolean isIncoming() {
		if (type == INCOMING) return true;
		return false;
	}
	
	public boolean isOutgoing() {
		if (type == OUTGOING) return true;
		return false;
	}
	
	public static final XSLT load(File configFile) throws JDOMException, IOException, IllegalArgumentException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		SAXBuilder builder = new SAXBuilder();
		Document document = builder.build(configFile);
		XSLT xslt = (XSLT)XMLSerialization.fromXML(document, Thread.currentThread().getContextClassLoader());
		return xslt;
	}
	
	public static final void save(XSLT xslt, File configFile) throws IllegalArgumentException, IOException, IllegalAccessException, InvocationTargetException {
		XMLOutputter outputter = new XMLOutputter();
		FileOutputStream fos = new FileOutputStream(configFile);
		outputter.output(XMLSerialization.toXML(xslt, false), fos);
		fos.flush();
		fos.close();
	}
	
	public static final boolean delete(XSLT xslt) {
		File directory = new File(Uploader.directory, ".xslts");
		String extension;
		if (xslt.isIncoming()) {
			extension = ".incoming.config";
		} else {
			extension = ".outgoing.config";
		}
		File configFile = new File(directory, xslt.getName() + extension);
		File xsltFile = new File(directory, xslt.getFilename());
		if ((xsltFile.delete()) && (configFile.delete())) {
			if (xslt.isIncoming()) {
				ServiceManager.getInstance().unregisterIncomingXSLT(xslt);
			} else {
				ServiceManager.getInstance().unregisterOutgoingXSLT(xslt);
			}
			return true;
		}
		return false;
	}
}
